package com.rk.kbk.controller;

import com.rk.kbk.controller.util.wxpay.util.WXpayCore;
import com.rk.kbk.controller.util.wxpay.util.WXpayXmlUtils;
import com.rk.kbk.controller.util.wxpayRide.util.WXpayCoreRide;
import com.rk.kbk.dao.CashRecordDao;
import com.rk.kbk.dao.OrderDao;
import com.rk.kbk.dao.OrderGoodsDao;
import com.rk.kbk.model.CashRecord;
import com.rk.kbk.model.Order;
import com.rk.kbk.model.OrderGoods;
import com.rk.kbk.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * Created by bilibili on 2017/5/9.
 */
@CrossOrigin
@RestController
@Transactional
@RequestMapping(value="/api/payOver")
public class PayOverController {
@Autowired
private OrderDao orderDao;
@Autowired
private CashRecordDao cashRecordDao;
@Autowired
private OrderGoodsDao orderGoodsDao;

    /**
     * 增加小费重新发单
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/wxpay/addTip",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public String addTip(HttpServletRequest request) throws IOException {
        System.out.println("微信支付回调");
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        String resultxml = new String(outSteam.toByteArray(), "utf-8");
        Map<String, String> params = WXpayXmlUtils.xml2map(resultxml);
        outSteam.close();
        inStream.close();
        if (!WXpayCore.checkSign(params)) {
            // 支付失败
            return "fail";
        } else {
            System.out.println("===============付款成功==============");
            // ------------------------------
            // 处理业务开始
            // 此处处理订单状态，结合自己的订单数据完成订单状态的更新
            String total_fee = params.get("total_fee");
            double money = Double.valueOf(total_fee) / 100;
            Long orderId = Long.valueOf(params.get("out_trade_no").split("a")[0]);

            Order order=orderDao.findOne(orderId);
            User user=order.getShop();
            Integer userType=user.getUserType();
            /****************************支明付细**********************************/
            CashRecord cashRecord = new CashRecord();
            cashRecord.setUser(user);
            String title="新增小费重新发单(微信支付"+money+"元)";
            cashRecord.setTitle(title);
            cashRecord.setTransactionNum(params.get("transaction_id"));//交易单号
            //  cashRecord.setOrderNumber();
            cashRecord.setOrderType(1);//1表示配送订单，2表示商城订单，3表示其他
            cashRecord.setOrderNumber(order.getOrderNumber());//订单编码
            cashRecord.setRecoedType(3);//流水类型，1表示充值，2表示提现，3表示消费扣钱
            cashRecord.setMoney(-money);
            cashRecord.setPayType(3);//支付类型：1表示余额支付，2表示支付宝支付，3表示微信支付
            cashRecord.setStatus(1);
            cashRecord.setGivePerson(1);
            cashRecordDao.save(cashRecord);//保存支付记录
            //updateUserPay(userId, String.valueOf(v));

            // 处理业务完毕
            // ------------------------------

            return "success";
        }
    }


    /**
     * 变更订单
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/wxpay/changeOrder",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public String changeOrder(HttpServletRequest request) throws IOException {
        System.out.println("微信支付回调");
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        String resultxml = new String(outSteam.toByteArray(), "utf-8");
        Map<String, String> params = WXpayXmlUtils.xml2map(resultxml);
        outSteam.close();
        inStream.close();
        if (!WXpayCore.checkSign(params)) {
            // 支付失败
            return "fail";
        } else {
            System.out.println("===============付款成功==============");
            // ------------------------------
            // 处理业务开始
            // 此处处理订单状态，结合自己的订单数据完成订单状态的更新
            String total_fee = params.get("total_fee");
            double money = Double.valueOf(total_fee) / 100;
            Long orderId = Long.valueOf(params.get("out_trade_no").split("a")[0]);

            Order order=orderDao.findOne(orderId);
            User user=order.getShop();
            Integer userType=user.getUserType();
            /****************************支付明细**********************************/
            CashRecord cashRecord = new CashRecord();
            cashRecord.setUser(user);
            String title="配送订单变更付款金额"+money+"元";
            cashRecord.setTitle(title);
            cashRecord.setTransactionNum(params.get("transaction_id"));//交易单号
            //  cashRecord.setOrderNumber();
            cashRecord.setOrderType(1);//1表示配送订单，2表示商城订单，3表示其他
            cashRecord.setOrderNumber(order.getOrderNumber());//订单编码
            cashRecord.setRecoedType(3);//流水类型，1表示充值，2表示提现，3表示消费扣钱
            cashRecord.setMoney(-money);
            cashRecord.setPayType(3);//支付类型：1表示余额支付，2表示支付宝支付，3表示微信支付
            cashRecord.setStatus(1);
            cashRecord.setGivePerson(1);
            cashRecordDao.save(cashRecord);//保存支付记录
            //updateUserPay(userId, String.valueOf(v));

            // 处理业务完毕
            // ------------------------------
            return "success";
//            return JsonResp.ok(order.getExceptLog());
        }
    }

    /**
     * 商城订单
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/wxpay/goodsOrderSuccess",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public String goodsOrderSuccess(HttpServletRequest request) throws IOException {
        System.out.println("微信支付回调");
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        String resultxml = new String(outSteam.toByteArray(), "utf-8");
        Map<String, String> params = WXpayXmlUtils.xml2map(resultxml);
        outSteam.close();
        inStream.close();
        Long orderId = Long.valueOf(params.get("out_trade_no").split("a")[0]);
        OrderGoods orderGoods=orderGoodsDao.findOne(orderId);
        User user=orderGoods.getUser();
        Integer userType=user.getUserType();
        if(userType==2){ //骑手端
            if (!WXpayCoreRide.checkSign(params)) {
                // 支付失败
                return "fail";
            }
        }else if(userType==3){ //商家端
            if (!WXpayCore.checkSign(params)) {
                // 支付失败
                return "fail";
            }
        }

            System.out.println("===============付款成功==============");
            // ------------------------------
            // 处理业务开始
            // 此处处理订单状态，结合自己的订单数据完成订单状态的更新
            String total_fee = params.get("total_fee");
            double money = Double.valueOf(total_fee) / 100;
            /****************************支付明细**********************************/
            CashRecord cashRecord = new CashRecord();
            cashRecord.setUser(user);
            String title="商城订单付款金额"+money+"元(微信)";
            cashRecord.setTitle(title);
            cashRecord.setTransactionNum(params.get("transaction_id"));//交易单号
            //  cashRecord.setOrderNumber();
            cashRecord.setOrderType(2);//1表示配送订单，2表示商城订单，3表示其他
            cashRecord.setOrderNumber(orderGoods.getOrderNumber());//订单编码
            cashRecord.setRecoedType(3);//流水类型，1表示充值，2表示提现，3表示消费扣钱
            cashRecord.setMoney(-money);
            cashRecord.setPayType(3);//支付类型：1表示余额支付，2表示支付宝支付，3表示微信支付
            if(userType==2){
                cashRecord.setGivePerson(2);
                cashRecord.setReceivePerson(0);
            }else if(userType==3){
                cashRecord.setGivePerson(1);
                cashRecord.setReceivePerson(0);
            }
            cashRecord.setStatus(1);
            cashRecordDao.save(cashRecord);//保存支付记录
            //updateUserPay(userId, String.valueOf(v));

            // 处理业务完毕
            // ------------------------------
           return "success";
          //  return JsonResp.ok(orderGoods);

    }




}
